<template>
  <div class="payable-report">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 日期范围 -->
      <el-form-item label="日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          default-value="[new Date('2025-06-01'), new Date('2025-06-26')]"
        />
      </el-form-item>

      <!-- 供应商选择（弹窗） -->
      <el-form-item label="供应商">
        <el-button type="primary" @click="openDialog('supplier')">
          {{ selectedSupplier.label || "请选择供应商" }}
        </el-button>
      </el-form-item>

      <!-- 业务员选择（弹窗） -->
      <el-form-item label="业务员">
        <el-button type="primary" @click="openDialog('salesman')">
          {{ selectedSalesman.label || "请选择业务员" }}
        </el-button>
      </el-form-item>

      <!-- 供应商类别选择（树弹窗） -->
      <el-form-item label="供应商类别">
        <el-button type="primary" @click="openDialog('category')">
          {{ selectedCategory.label || "请选择类别" }}
        </el-button>
      </el-form-item>

      <!-- 无欠款过滤 -->
      <el-form-item>
        <el-checkbox v-model="filter.hideZero">不显示无欠款供应商</el-checkbox>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="info" @click="resetFilter">重置</el-button>
        <el-button type="primary" @click="queryData">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 供应商选择弹窗 ========== -->
    <el-dialog
      title="选择供应商"
      v-model="dialogs.supplier.visible"
      width="640px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.supplier.keyword"
          placeholder="输入编号/名称/联系人"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.supplier.showDisabled" class="ml-4"
          >显示禁用供应商</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSuppliers"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.supplier.list"
        :row-key="(row) => row.id"
        @selection-change="handleSupplierSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="供应商编号" min-width="120" />
        <el-table-column prop="name" label="供应商名称" min-width="180" />
        <el-table-column prop="category" label="类别" min-width="120" />
        <el-table-column
          prop="initialPayable"
          label="期初应付款"
          align="right"
          min-width="120"
        />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.supplier.limit = val)"
        @current-change="(val) => (dialogs.supplier.page = val)"
        :current-page="dialogs.supplier.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.supplier.limit"
        :total="dialogs.supplier.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.supplier.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('supplier')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 业务员选择弹窗 ========== -->
    <el-dialog
      title="选择业务人员"
      v-model="dialogs.salesman.visible"
      width="540px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.salesman.keyword"
          placeholder="输入编号/名称"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.salesman.showDisabled" class="ml-4"
          >显示禁用人员</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSalesmen"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.salesman.list"
        :row-key="(row) => row.id"
        @selection-change="handleSalesmanSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="职员编号" min-width="120" />
        <el-table-column prop="name" label="职员名称" min-width="180" />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.salesman.limit = val)"
        @current-change="(val) => (dialogs.salesman.page = val)"
        :current-page="dialogs.salesman.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.salesman.limit"
        :total="dialogs.salesman.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.salesman.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('salesman')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 供应商类别选择弹窗（树结构） ========== -->
    <el-dialog
      title="选择供应商类别"
      v-model="dialogs.category.visible"
      width="360px"
    >
      <el-tree
        :data="categoryTree"
        show-checkbox
        node-key="id"
        :props="{ label: 'label', children: 'children' }"
        @check="handleCategoryCheck"
        default-expand-all
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.category.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('category')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 应付账款表格 ========== -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      show-summary
      :summary-method="generateSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column prop="supplier" label="供应商" min-width="180" />
      <el-table-column prop="salesman" label="业务员" min-width="120" />
      <el-table-column prop="docDate" label="单据日期" min-width="120" />
      <el-table-column prop="docNo" label="单据编号" min-width="150" />
      <el-table-column prop="bizType" label="业务类型" min-width="120" />
      <el-table-column
        prop="addPayable"
        label="增加应付款"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="addPrepay"
        label="增加预付款"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="balance"
        label="应付款余额"
        align="right"
        min-width="120"
      />
      <el-table-column prop="remark" label="备注" min-width="200" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  supplier: [], // 选中的供应商（数组）
  salesman: [], // 选中的业务员（数组）
  category: [], // 选中的类别（树节点）
  hideZero: false, // 不显示无欠款
});

// ========== 选中项回显 ==========
const selectedSupplier = ref({ label: "" });
const selectedSalesman = ref({ label: "" });
const selectedCategory = ref({ label: "" });

// ========== 对话框状态 ==========
const dialogs = reactive({
  supplier: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的供应商行
  },
  salesman: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的业务员行
  },
  category: {
    visible: false,
    selected: [], // 选中的树节点
  },
});

// ========== 基础数据模拟 ==========
// 供应商类别树（示例）
const categoryTree = ref([
  {
    id: 1,
    label: "广东",
    children: [
      { id: 11, label: "海鲜供应商" },
      { id: 12, label: "食品供应商" },
    ],
  },
  {
    id: 2,
    label: "全国",
    children: [
      { id: 21, label: "酒水饮料供应商" },
      { id: 22, label: "测试类别" },
    ],
  },
]);

// 模拟供应商列表
const mockSuppliers = [
  {
    id: 1,
    code: "G00001",
    name: "商品综合批发有限公司",
    category: "食品供应商",
    initialPayable: 13881.78,
  },
  {
    id: 2,
    code: "G00002",
    name: "金小蝶食品贸易有限...",
    category: "食品供应商",
    initialPayable: 16446.44,
  },
  {
    id: 3,
    code: "G00003",
    name: "广州食品批发有限公司",
    category: "食品供应商",
    initialPayable: 9555.65,
  },
  {
    id: 4,
    code: "G00004",
    name: "深圳食品加工有限公司",
    category: "食品供应商",
    initialPayable: 16698.12,
  },
  {
    id: 5,
    code: "G00005",
    name: "食品零售供应商",
    category: "食品供应商",
    initialPayable: 12634.7,
    salesman: "采购-小陈",
  },
  {
    id: 6,
    code: "G00006",
    name: "零食供应商",
    category: "食品供应商",
    initialPayable: 11799.4,
  },
  {
    id: 7,
    code: "G00007",
    name: "测试供应商",
    category: "测试类别",
    initialPayable: 0,
  },
];

// 模拟业务员列表
const mockSalesmen = [
  { id: 1, code: "D0001", name: "老板" },
  { id: 2, code: "D0002", name: "财务-玲" },
  { id: 3, code: "D0003", name: "采购-小陈" },
  { id: 4, code: "D0004", name: "采购-小王" },
  { id: 5, code: "D0005", name: "销售-小李" },
];

// ========== 对话框交互逻辑 ==========
/** 打开对话框 */
const openDialog = (type) => {
  dialogs[type].visible = true;
  if (type === "supplier") fetchSuppliers();
  if (type === "salesman") fetchSalesmen();
};

/** 获取供应商列表（模拟） */
const fetchSuppliers = () => {
  dialogs.supplier.list = mockSuppliers.filter(
    (item) =>
      item.name.includes(dialogs.supplier.keyword) ||
      item.code.includes(dialogs.supplier.keyword)
  );
  dialogs.supplier.total = dialogs.supplier.list.length;
};

/** 获取业务员列表（模拟） */
const fetchSalesmen = () => {
  dialogs.salesman.list = mockSalesmen.filter(
    (item) =>
      item.name.includes(dialogs.salesman.keyword) ||
      item.code.includes(dialogs.salesman.keyword)
  );
  dialogs.salesman.total = dialogs.salesman.list.length;
};

/** 供应商选择事件 */
const handleSupplierSelect = (val) => {
  dialogs.supplier.selected = val;
};

/** 业务员选择事件 */
const handleSalesmanSelect = (val) => {
  dialogs.salesman.selected = val;
};

/** 类别选择事件（树） */
const handleCategoryCheck = (val) => {
  dialogs.category.selected = val;
};

/** 确认选择 */
const confirmSelection = (type) => {
  let label = "";
  if (type === "supplier") {
    if (dialogs.supplier.selected.length === 0) {
      ElMessage.warning("请选择供应商");
      return;
    }
    label = dialogs.supplier.selected.map((item) => item.name).join("、");
    filter.supplier = dialogs.supplier.selected;
  } else if (type === "salesman") {
    if (dialogs.salesman.selected.length === 0) {
      ElMessage.warning("请选择业务员");
      return;
    }
    label = dialogs.salesman.selected.map((item) => item.name).join("、");
    filter.salesman = dialogs.salesman.selected;
  } else if (type === "category") {
    if (dialogs.category.selected.length === 0) {
      ElMessage.warning("请选择类别");
      return;
    }
    label = dialogs.category.selected.map((item) => item.label).join("、");
    filter.category = dialogs.category.selected;
  }

  // 更新回显
  if (type === "supplier") selectedSupplier.value.label = label;
  if (type === "salesman") selectedSalesman.value.label = label;
  if (type === "category") selectedCategory.value.label = label;

  // 关闭对话框
  dialogs[type].visible = false;
  ElMessage.success("选择成功！");
};

/** 重置筛选 */
const resetFilter = () => {
  filter.dateRange = [new Date("2025-06-01"), new Date("2025-06-26")];
  filter.supplier = [];
  filter.salesman = [];
  filter.category = [];
  filter.hideZero = false;
  selectedSupplier.value.label = "";
  selectedSalesman.value.label = "";
  selectedCategory.value.label = "";
  ElMessage.success("筛选条件已重置");
};

// ========== 表格数据模拟 ==========
const tableData = ref([]);

/** 查询数据（模拟） */
const queryData = () => {
  // 1. 筛选供应商（模拟逻辑）
  let filteredSuppliers = mockSuppliers;
  if (filter.supplier.length > 0) {
    filteredSuppliers = filteredSuppliers.filter((item) =>
      filter.supplier.some((s) => s.id === item.id)
    );
  }
  if (filter.hideZero) {
    filteredSuppliers = filteredSuppliers.filter(
      (item) => item.initialPayable > 0
    );
  }

  // 2. 构建表格数据（每个供应商生成「期初余额」和「小计」行）
  const result = [];
  filteredSuppliers.forEach((supplier) => {
    // 期初余额行
    result.push({
      supplier: supplier.name,
      salesman: supplier.salesman || "",
      docDate: "",
      docNo: "",
      bizType: "期初余额",
      addPayable: 0,
      addPrepay: 0,
      balance: supplier.initialPayable,
      remark: "",
    });
    // 小计行（与期初一致，实际需计算汇总）
    result.push({
      supplier: supplier.name,
      salesman: supplier.salesman || "",
      docDate: "",
      docNo: "",
      bizType: "小计",
      addPayable: 0,
      addPrepay: 0,
      balance: supplier.initialPayable,
      remark: "",
    });
  });
  tableData.value = result;
};

/** 合计行计算 */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (column.prop === "balance") {
      const total = data.reduce((acc, item) => acc + item.balance, 0);
      sums[index] = total.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// ========== 初始化 ==========
onMounted(() => {
  queryData(); // 初始加载数据
});
</script>

<style scoped>
.payable-report {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>